package com.yuncommunity.cloudlab.utils

import okhttp3.OkHttpClient
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.http.HttpServletRequest

object MyUtils {
    fun timeStamp(): String {
        return SimpleDateFormat("yyyyMMddHHmmss").format(Date())
    }

    fun timeHMS(): String {
        return SimpleDateFormat("HHmmss").format(Date())
    }

    fun getOutOrderNum(): String {
        return timeStamp() + ThreadLocalRandom.current().nextInt(1000, 9999)
    }

    /**
     * 根据文件名获取后缀
     */
    fun getExtByName(originalFilename: String): String {
        return originalFilename.substring(originalFilename.indexOf(".") - 1)
    }

    fun readRequest(request: HttpServletRequest?): String? {
        val inputStream: InputStream
        val sb = StringBuffer()
        inputStream = request!!.inputStream
        var str: String?
        val `in` = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
        while (`in`.readLine().also { str = it } != null) {
            sb.append(str)
        }
        `in`.close()
        inputStream.close()
        return sb.toString()
    }

    fun randomInt(length: Int): String {
        var res = ""
        for (i in 0 until length) {
            res += (Math.random() * 10).toInt()
        }
        return res
    }

    fun sqlAnd(sql: String, args: List<Any>): String {
        return if (args.size == 0) {
            "$sql where "
        } else "$sql and "
    }

    fun zeroNum(num: Int, length: Int): String {
        var str = num.toString()
        do {
            str = "0$str"
        } while (str.length < length)
        return str
    }

    fun getFileName(filePath: String): String {
        if (filePath == "") {
            return ""
        }
        var names = filePath.split("/")
        return names[names.size - 1]
    }
}